package com.zhangmeng.tools.controller;


import cn.hutool.core.lang.Console;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.ImagePath;
import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.MapValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelFileReadController {

    @FXML
    public Button file_choose;

    @FXML
    public TableView<Map<String, SimpleStringProperty>> result_view;

    private final ObservableList<Map<String, SimpleStringProperty>> result_list = FXCollections.observableArrayList();

    @FXML
    public TextField file_path;

    private final SimpleObjectProperty<File> choose_file = new SimpleObjectProperty<>(null);

    @FXML
    public Button open_excel;

    @FXML
    public void initialize() {
        result_view.setItems(result_list);
        file_choose.setText(null);
        ImageView iv = new ImageView(new Image(ImagePath.path(ImagePath.ImagePathType.IMAGE_FILE)));
        iv.setPreserveRatio(true);
        iv.setFitWidth(18);
        file_choose.setGraphic(iv);

        //选择文件
        file_choose.setOnAction(event -> choose_file());

        //打开文件
        open_excel.setOnAction(event -> {

            if (choose_file.getValue() == null) {
                AlertUtils.alert_warning("请选择将要识别的pdf再试!");
                return;
            }

            Stage alert = AlertUtils.alert_loading(file_choose.getScene().getWindow());
            new Thread(() -> {
                //打开文件
                readBySax();
                Platform.runLater(() -> {
                    log.info("打开文件.....");
                    alert.close();
                });
            }).start();
        });
    }

    public void choose_file() {
        Stage stage = new Stage();
        FileChooser dc = new FileChooser();
        dc.setTitle("文件选择");
        dc.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("类型", "*.xlsx"));
        File file = dc.showOpenDialog(stage);
        if (file != null) {
            String path = file.getAbsolutePath();
            file_path.setText(path);
            log.info("file_path:{}", path);
            choose_file.set(file);
        }
    }

    public void readBySax() {
        ExcelReader reader = ExcelUtil.getReader(choose_file.getValue());
        List<Map<String, Object>> mapList = reader.readAll();
//        for (int i = 1; i <= mapList.size(); i++) {
//            Map<String, Object> map = mapList.get(i-1);
//            map.put("id",i);
//        }
        update_stage(mapList);
    }

    public void update_stage(List<Map<String, Object>> list) {
        result_list.clear();
        result_view.getColumns().clear();
        Platform.runLater(() -> {
            if (list.size() > 0) {
                Map<String, Object> map1 = list.get(0);
                for (Map.Entry<String, Object> entry : map1.entrySet()) {
                    String key = entry.getKey();
                    TableColumn<Map<String, SimpleStringProperty>, String> column = new TableColumn<>(key);
                    column.setCellValueFactory(new MapValueFactory(key));
                    result_view.getColumns().add(column);
                }

                for (Map<String, Object> map : list) {
                    Map<String, SimpleStringProperty> map2 = new HashMap<>();
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue() == null ? "" : entry.getValue().toString();
                        map2.put(key, new SimpleStringProperty(value));
                    }
                    result_list.add(map2);
                }
            }
        });
    }

    public String str_print(String obj) {
        byte[] bytes = obj.getBytes(StandardCharsets.UTF_8);
        return StringUtils.toEncodedString(bytes, Charset.forName("GBK"));
    }
}
